package com.contactsconverter.activity;

import java.util.Locale;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.contactsconverter.utils.CTUtils;
import com.contactsconverter.volley.CTRequestQueue;
import com.contactsconverter.R;

import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.text.TextUtils;
import android.util.JsonWriter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */

public class CTLoginActivity extends AccountAuthenticatorActivity {

	public static final String PARAM_AUTHTOKEN_TYPE = "auth.token";  
	public static final String PARAM_CREATE = "create";  
	public static final int REQ_CODE_CREATE = 1;  
	public static final int REQ_CODE_UPDATE = 2;  
	public static final String EXTRA_REQUEST_CODE = "req.code";  
	public static final int RESP_CODE_SUCCESS = 0;  
	public static final int RESP_CODE_ERROR = 1;  
	public static final int RESP_CODE_CANCEL = 2;  
	// Values for email and password at the time of the login attempt.
	private String mEmail;
	private String mPhone;
	private String mCode;
	private String mZipCode;

	// UI references.
	private EditText mEmailView;
	private EditText mPhoneView;
	private EditText mCodeView;
	private EditText mZipCodeView;

	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		//		getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
		//		final ActionBar actionBar = getSupportActionBar();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fllogin);
		
		
		// Set up the login form.

		mEmailView = (EditText) findViewById(R.id.email);
		mPhoneView = (EditText) findViewById(R.id.phone);	
	//	mCodeView = (EditText) findViewById(R.id.code_authentification);	
		
		//mZipCodeView = (EditText) findViewById(R.id.fl_login_zip_code);
//		findViewById(R.id.sign_in_button).setOnClickListener(
//				new View.OnClickListener() {
//					@Override
//					public void onClick(View view) {
//						attemptLogin();
//					}
//				});
		findViewById(R.id.register_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptRegister();
					}
				});
//		findViewById(R.id.fl_register_retry).setOnClickListener(
//				new View.OnClickListener() {
//					@Override
//					public void onClick(View view) {
//						onRetry();
//					}
//				});
//		findViewById(R.id.fl_login_retry).setOnClickListener(
//				new View.OnClickListener() {
//					@Override
//					public void onClick(View view) {
//						onRetryLogin();
//					}
//				});
//		((TextView)findViewById(R.id.fl_login_retry)).setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
//		((TextView)findViewById(R.id.fl_register_retry)).setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
		//((EditText)findViewById(R.id.fl_login_zip_code)).setText(getCountryZipCode());
		mZipCode = getCountryZipCode();
		Spinner spinner = (Spinner) findViewById(R.id.fl_login_zip_code);
		spinner.setSelection(getContryByCodeZip(mZipCode));

		onRetryLogin();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		return false;
	}

	private void onRetry(){
		
		mEmail = CTUtils.getPreference(CTUtils.ACCOUNT_EMAIL, this);
		if(mEmail!=null|| "".equals(mEmail.trim())) 
		{
			((EditText)findViewById(R.id.email)).setText(mEmail);
		}
		
		findViewById(R.id.register_form).setVisibility(View.VISIBLE);
	//	findViewById(R.id.login_form).setVisibility(View.GONE);
	}
	private void onRetryLogin(){
		 mEmail = CTUtils.getPreference(CTUtils.ACCOUNT_EMAIL, this);
		if(mEmail==null|| "".equals(mEmail.trim()))
		{
			Toast.makeText(this, this.getString(R.string.ct_registrer_before_login), Toast.LENGTH_LONG).show();
			onRetry();
			
		}
		else{
		//	findViewById(R.id.register_form).setVisibility(View.GONE);
			//findViewById(R.id.login_form).setVisibility(View.VISIBLE);
		}
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {

		finish();

		// Reset errors.
		mCodeView.setError(null);

		// Store values at the time of the login attempt.
		mCode = mCodeView.getText().toString();

		String DEFAULT_SERVER_URL = getResources().getString(R.string.default_server_url);

		String SERVICE_AUTH_URL = "rest/user/confirm/email/%s/code/%s";
		String url = String.format(DEFAULT_SERVER_URL+SERVICE_AUTH_URL, mEmail, mCode);
		onLogin(url);

	}
	private void onLogin(String url){
		Log.e(CTLoginActivity.class.getName(), url);
		showProgress(true); 
		//new JsonWriter(out)
		JsonObjectRequest jsObjRequest = new JsonObjectRequest
		(Method.POST, url,null, new Response.Listener<JSONObject>() {

			@Override
			public void onResponse(JSONObject jsonObject) {
				try {		
					Log.e(CTLoginActivity.class.getName(), jsonObject+"");
					showProgress(false);
					onLoginSuccess(jsonObject);					
					
				} catch (JSONException e) {

					e.printStackTrace();
				}

			}		    
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e(CTLoginActivity.class.getName(), "Mauvais ");
				showProgress(false);
				onLoginFail(error);

			}
		});

		CTRequestQueue.getInstance(this.getApplicationContext()).addToRequestQueue(jsObjRequest);
	}
	private void onLoginSuccess(JSONObject jsonObject) throws JSONException{

	
		AccountManager accMgr = AccountManager.get(this);  		
		final Account account = new Account(jsonObject.getString("email"), CTUtils.ACCOUNT_TYPE);  
		accMgr.addAccountExplicitly(account, jsonObject.getString("code"), null);  

		// Now we tell our caller, could be the Andreoid Account Manager or even our own application  
		// that the process was successful  

		final Intent intent = new Intent();  
		intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mEmail);  
		intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, CTUtils.ACCOUNT_TYPE);  
		intent.putExtra(AccountManager.KEY_AUTHTOKEN, CTUtils.ACCOUNT_TYPE);  
		this.setAccountAuthenticatorResult(intent.getExtras());  
				
		CTUtils.savePreference(CTUtils.LOGINSUCCESS, "1024", this);
		this.setResult(RESULT_OK, intent);  
		//this.finish();  
		
	}
	private void onLoginFail(VolleyError error){
		Toast.makeText(this, this.getString(R.string.error_invalid_authentification), Toast.LENGTH_LONG).show();
		//finish();		
		CTUtils.savePreference(CTUtils.LOGINSUCCESS, "1025", this); 
		//this.finish();
		
	}
	public void attemptRegister() {
		
		mEmailView.setError(null);
		mPhoneView.setError(null);
		//		mZipCodeView.setError(null);
		// Store values at the time of the login attempt.
		mEmail = mEmailView.getText().toString();

		// Check for a valid email address.
		if (!isValidEmail(mEmail)) {
			mEmailView.setError(getString(R.string.error_invalid_email));
			mEmailView.requestFocus();
			return;
		}

		//		// Check for a valid phone number.
		mPhone = mPhoneView.getText().toString();
		//Toast.makeText(this, "mPhone="+mPhone, Toast.LENGTH_LONG).show();
		if (!isValidPhone(mPhone)) {
			mPhoneView.setError(getString(R.string.error_invalid_phone));
			mPhoneView.requestFocus();
			return;
		}

		if(mPhone.startsWith("0")){
			mPhone.replaceFirst("0", "");

		}
		String countryZipCode = "00"+mZipCode;
		//
		String DEFAULT_SERVER_URL = getResources().getString(R.string.default_server_url);

		String SERVICE_AUTH_URL = "rest/user/create/email/%s/phone/%s/firstname/%s/lastname/%s/language/%s/codeappli/%s";

		//
		//

		String[]  langCode = Locale.getDefault().getLanguage().split("_");
		String url = String.format(DEFAULT_SERVER_URL+SERVICE_AUTH_URL, mEmail, countryZipCode+ mPhone, mEmail, mEmail, langCode[0],getString(R.string.codeappli));
		
		Log.e(CTLoginActivity.class.getName(), url);
		onRegister(url);
	}
	public final static boolean isValidEmail(CharSequence target) {
		return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();

	}
	public final static boolean isValidPhone(CharSequence target) {
		return !TextUtils.isEmpty(target) && android.util.Patterns.PHONE.matcher(target).matches();

	}

	private void showProgress(final boolean show) {
		if(show)
			progressDialog = ProgressDialog.show(CTLoginActivity.this, "", "Loading...");
		else
		{
			progressDialog.cancel();
			progressDialog.dismiss();
	
		}
	}

	private void onRegister(String url){

		showProgress(true);
		JsonObjectRequest jsObjRequest = new JsonObjectRequest
				(Method.POST, url,null, new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject jsonObject) {
						try {		
							showProgress(false);
							onRegisterSuccess(jsonObject);
							
						} catch (JSONException e) {

							e.printStackTrace();
						}

					}		    
				}, new Response.ErrorListener() {
					@Override

					public void onErrorResponse(VolleyError error) {	
						showProgress(false);

						onRegisterFail(error);
						
					}
				});

		CTRequestQueue.getInstance(this.getApplicationContext()).addToRequestQueue(jsObjRequest);
	}
	private void onRegisterSuccess(JSONObject jsonObject) throws JSONException{

		CTUtils.savePreference(CTUtils.ACCOUNT_EMAIL, mEmail, this);
		
		AccountManager accMgr = AccountManager.get(this);  		
		final Account account = new Account(jsonObject.getString("email"), CTUtils.ACCOUNT_TYPE);  
		accMgr.addAccountExplicitly(account, jsonObject.getString("email"), null);  

		// Now we tell our caller, could be the Andreoid Account Manager or even our own application  
		// that the process was successful  

		final Intent intent = new Intent();  
		intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mEmail);  
		intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, CTUtils.ACCOUNT_TYPE);  
		intent.putExtra(AccountManager.KEY_AUTHTOKEN, CTUtils.ACCOUNT_TYPE);  
		this.setAccountAuthenticatorResult(intent.getExtras());  
				
		CTUtils.savePreference(CTUtils.LOGINSUCCESS, "1024", this);
		this.setResult(RESULT_OK, intent);  
		finish();
		//onRetryLogin();	

		//Log.e(CTLoginActivity.class.getName(), jsonObject+"");


	}
	private void onRegisterFail(VolleyError error) {
		//onRetry();
		//Log.e("", error.getMessage(), error.getCause());
		Toast.makeText(this, getString(R.string.alerte_de_connexion), Toast.LENGTH_SHORT).show();
	}

	@Override
	public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
		super.onKeyDown(keyCode, event);
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			setResult(1200);

		}

		return true;

	}
	public String getCountryZipCode(){

		String CountryID="";
		String CountryZipCode = getString(R.string.default_zip_code);

		TelephonyManager manager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
		CountryID= manager.getSimCountryIso().toUpperCase();
		String[] rl=this.getResources().getStringArray(R.array.CountryCodes);
		for(int i=0;i<rl.length;i++){
			String[] g = rl[i].split(",");
			if(g[1].trim().equals(CountryID.trim())){
				CountryZipCode=g[0];break;  }
		}
		return CountryZipCode;
	}

	private int getContryByCodeZip(String codeZip){ 

		String[] country = getResources().getStringArray(R.array.countries_zip);
		int i = 0;
		for (String string : country) {
			if(string.contains("(+"+codeZip+")"))
				return i;
			i++;
		}

		return 0;



	}
}
